// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
}) // 使用当前云环境

const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const data = null
  if(event.flag == 'add'){
    data = await db.collection('SJBL_User').add({
      data:{
        openid: wxContext.OPENID,
        nickname: event.nickname,
        avatarurl: event.avatarurl,
        gender: event.gender,
      }
    })
  }else{
    const data = await db.collection('SJBL_User').where({
      openid: wxContext.OPENID
    }).update({
      data: {
        avatarurl: event.avatarurl,
        gender: event.gender,
        nickname: event.nickname,
        telnum: event.telnum
      }
    }).then(res => {
      console.log('用户更新', res)
    }).catch(err => {
      console.error('用户更新失败', err)
    })
  }
  
  return {
    event,
    openid: wxContext.OPENID,
    appid: wxContext.APPID,
    unionid: wxContext.UNIONID,
    data
  }
}